(function () {
    console.log('[联动绑定] 脚本已加载');

    // 检查是否在 iframe 中
    const isInIframe = window !== window.top;
    const isTargetIframe = isInIframe && window.location.hostname === 'admin-daily.hszq.com.cn';

    console.log('[联动绑定] 是否在iframe中:', isInIframe);
    console.log('[联动绑定] 是否在目标iframe中:', isTargetIframe);
    console.log('[联动绑定] 当前URL:', window.location.href);

    const COPY_MODAL_TIMEOUT = 8000;
    let copyFeatureInitialized = false;
    let copyFeatureCheckTimer = null;
    let pendingCopyTask = null;

    // 只在目标 iframe 中执行
    if (!isTargetIframe) {
        console.log('[联动绑定] 不在目标iframe中，跳过执行');
        return;
    }

    function waitForPageReady() {
        return new Promise((resolve) => {
            // 检查页面是否已经完全加载
            if (document.readyState === 'complete') {
                console.log('[联动绑定] iframe页面已完全加载');
                resolve();
                return;
            }

            // 如果页面还在加载，等待 load 事件
            if (document.readyState === 'loading') {
                console.log('[联动绑定] iframe页面仍在加载，等待DOMContentLoaded事件');
                document.addEventListener('DOMContentLoaded', () => {
                    console.log('[联动绑定] iframe DOMContentLoaded事件已触发');
                    // DOMContentLoaded 后再等待一段时间确保页面渲染完成
                    setTimeout(resolve, 500);
                });
            } else {
                // interactive 状态，等待 load 事件
                console.log('[联动绑定] iframe页面交互状态，等待load事件');
                window.addEventListener('load', () => {
                    console.log('[联动绑定] iframe窗口load事件已触发');
                    setTimeout(resolve, 300);
                });
            }
        });
    }

    function waitForElements() {
        return new Promise((resolve) => {
            let attempts = 0;
            const maxAttempts = 50; // 最多尝试 5 秒

            function check() {
                attempts++;
                console.log(`[联动绑定] 检查目标元素，第${attempts}次尝试`);

                // 检查页面是否有预期的元素
                const hasContent = document.querySelector('body > *') &&
                    document.body.children.length > 1;

                // 额外检查是否有你的目标元素（可选）
                const hasModalSystem = document.querySelector('.modal') ||
                    document.querySelector('#form-add-type') ||
                    document.body.innerHTML.length > 1000;

                if (hasContent && hasModalSystem) {
                    console.log('[联动绑定] 目标元素已找到');
                    resolve();
                } else if (attempts >= maxAttempts) {
                    console.warn('[联动绑定] 已达到最大尝试次数，继续执行');
                    resolve();
                } else {
                    setTimeout(check, 100);
                }
            }

            check();
        });
    }

    async function initBinder() {
        try {
            console.log('[联动绑定] 开始初始化');

            // 等待页面完全加载
            await waitForPageReady();

            // 等待关键元素出现
            await waitForElements();

            if (!document.body) {
                console.error('[联动绑定] 等待后body仍不可用');
                return;
            }

            console.log('[联动绑定] 页面准备就绪，开始监听');

            // 定义所有需要绑定的选择器对
            const selectorPairs = [
                { main: '#form-add-type', child: '#form-add-childType', name: '新增表单' },
                { main: '#form-edit-type', child: '#form-edit-childType', name: '编辑表单' },
                { main: '#filter-type', child: '#filter-childType', name: '筛选条件' }
            ];

            const boundMap = new Map();
            let prevHasModalOpen = document.body.classList.contains('modal-open');

            function bindSelectors(container, selectorPair) {
                const mainSelect = container.querySelector(selectorPair.main);
                const childSelect = container.querySelector(selectorPair.child);

                if (!mainSelect || !childSelect) {
                    return null;
                }

                console.log(`[联动绑定] 绑定${selectorPair.name}的联动选择器`);

                const allOptGroups = Array.from(childSelect.querySelectorAll('optgroup'));
                const changeHandler = () => {
                    const selectedType = mainSelect.value;
                    childSelect.innerHTML = '';
                    const matchedGroup = allOptGroups.find(g => g.dataset.type === selectedType);
                    if (matchedGroup) {
                        childSelect.appendChild(matchedGroup.cloneNode(true));
                    }
                };

                mainSelect.addEventListener('change', changeHandler);
                mainSelect.dispatchEvent(new Event('change'));

                return { mainSelect, changeHandler, name: selectorPair.name };
            }

            function bindModal(modal) {
                if (!modal || boundMap.has(modal)) return;

                console.log('[联动绑定] 尝试绑定模态框');

                const bindings = [];
                selectorPairs.forEach(pair => {
                    const binding = bindSelectors(modal, pair);
                    if (binding) {
                        bindings.push(binding);
                    }
                });

                if (bindings.length > 0) {
                    boundMap.set(modal, bindings);
                    console.log(`[联动绑定] 模态框绑定成功，共绑定${bindings.length}组选择器`);
                } else {
                    console.warn('[联动绑定] 模态框中未找到目标选择器，跳过');
                }
            }

            function bindPageSelectors() {
                console.log('[联动绑定] 尝试绑定页面级选择器');

                selectorPairs.forEach(pair => {
                    const binding = bindSelectors(document, pair);
                    if (binding) {
                        // 为页面级选择器创建特殊标识
                        const pageKey = `page-${pair.name}`;
                        boundMap.set(pageKey, [binding]);
                        console.log(`[联动绑定] 页面级${pair.name}绑定成功`);
                    }
                });
            }

            function unbindAll() {
                boundMap.forEach((bindings, key) => {
                    bindings.forEach(({ mainSelect, changeHandler, name }) => {
                        mainSelect.removeEventListener('change', changeHandler);
                        console.log(`[联动绑定] 解绑${name}选择器`);
                    });
                });
                boundMap.clear();
            }

            function handleModalOpen() {
                document.querySelectorAll('.modal.in').forEach(modal => {
                    if (!boundMap.has(modal)) bindModal(modal);
                });
            }

            // 初始化时绑定页面级选择器
            bindPageSelectors();

            const bodyObserver = new MutationObserver(() => {
                const curHas = document.body.classList.contains('modal-open');
                if (curHas && !prevHasModalOpen) {
                    console.log('[联动绑定] 检测到模态框打开');
                    setTimeout(handleModalOpen, 150);
                } else if (!curHas && prevHasModalOpen) {
                    console.log('[联动绑定] 检测到模态框关闭');
                    // 只解绑模态框相关的绑定，保留页面级绑定
                    setTimeout(() => {
                        const modalKeys = Array.from(boundMap.keys()).filter(key =>
                            typeof key !== 'string' || !key.startsWith('page-')
                        );
                        modalKeys.forEach(key => {
                            const bindings = boundMap.get(key);
                            bindings.forEach(({ mainSelect, changeHandler, name }) => {
                                mainSelect.removeEventListener('change', changeHandler);
                                console.log(`[联动绑定] 解绑模态框${name}选择器`);
                            });
                            boundMap.delete(key);
                        });
                    }, 150);
                }
                prevHasModalOpen = curHas;
            });

            bodyObserver.observe(document.body, { attributes: true, attributeFilter: ['class'] });

            console.log('[联动绑定] 初始化完成，正在监听body.class变化');

            initCopyFeature();

        } catch (error) {
            console.error('[联动绑定] 初始化失败:', error);
        }
    }

    // 入口 - 使用异步初始化
    initBinder();

    function initCopyFeature() {
        if (copyFeatureInitialized || copyFeatureCheckTimer) {
            return;
        }

        let attempts = 0;
        const maxAttempts = 50;
        copyFeatureCheckTimer = setInterval(() => {
            attempts++;
            const $ = window.jQuery;

            if (!$ || !$.fn || typeof $.fn.bootstrapTable !== 'function') {
                if (attempts >= maxAttempts) {
                    clearInterval(copyFeatureCheckTimer);
                    copyFeatureCheckTimer = null;
                    console.warn('[联动绑定] 复制功能初始化失败：未检测到jQuery或bootstrapTable');
                }
                return;
            }

            const $table = $('#page');
            const $addBtn = $('#filter-add');

            if ($table.length && $addBtn.length) {
                clearInterval(copyFeatureCheckTimer);
                copyFeatureCheckTimer = null;
                setupCopyFeature($table);
            } else if (attempts >= maxAttempts) {
                clearInterval(copyFeatureCheckTimer);
                copyFeatureCheckTimer = null;
                console.warn('[联动绑定] 复制功能初始化超时：未找到表格或新增按钮');
            }
        }, 200);
    }

    function setupCopyFeature($table) {
        if (copyFeatureInitialized) {
            return;
        }

        copyFeatureInitialized = true;
        console.log('[联动绑定] 复制按钮功能已启用');

        const refreshButtons = () => {
            try {
                injectCopyButtons($table);
            } catch (err) {
                console.error('[联动绑定] 注入复制按钮失败:', err);
            }
        };

        refreshButtons();
        $table.on('post-body.bs.table', refreshButtons);

        document.addEventListener('click', handleCopyButtonClick, false);

        if (window.jQuery) {
            window.jQuery(document).on('shown.bs.modal', handleCopyModalShown);
        }
    }

    function injectCopyButtons($table) {
        if (!window.jQuery) {
            return;
        }

        const $rows = $table.find('tbody tr');
        if (!$rows.length) {
            return;
        }

        $rows.each(function () {
            const $row = window.jQuery(this);
            if ($row.find('.jq-page-opt-copy').length) {
                return;
            }

            const $actionCell = $row.children('td').first();
            if (!$actionCell.length) {
                return;
            }

            const $editBtn = $actionCell.find('.jq-page-opt-edit, .jq-page-opt-edit-limited').first();
            if (!$editBtn.length) {
                return;
            }

            const btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'btn btn-xs btn-primary jq-page-opt-copy';
            btn.setAttribute('data-id', $editBtn.data('id'));
            btn.setAttribute('data-loading-text', '复制中...');
            btn.innerHTML = '<span class="glyphicon glyphicon-duplicate" aria-hidden="true"></span>&nbsp;复制';

            $editBtn[0].parentNode.insertBefore(btn, $editBtn[0]);
        });
    }

    function handleCopyButtonClick(event) {
        if (!copyFeatureInitialized || !window.jQuery) {
            return;
        }

        const copyBtn = findCopyButton(event.target);
        if (!copyBtn) {
            return;
        }

        event.preventDefault();
        event.stopPropagation();

        const $btn = window.jQuery(copyBtn);
        const hasBootstrapButton = typeof $btn.button === 'function';
        if (hasBootstrapButton) {
            $btn.button('loading');
        } else {
            copyBtn.disabled = true;
        }

        const rowData = getRowDataForButton(copyBtn);
        if (!rowData) {
            console.warn('[联动绑定] 未能获取复制行的数据');
            if (hasBootstrapButton) {
                $btn.button('reset');
            } else {
                copyBtn.disabled = false;
            }
            return;
        }

        const addBtn = document.querySelector('#filter-add');
        if (!addBtn) {
            console.warn('[联动绑定] 未找到新增按钮，无法执行复制');
            if (hasBootstrapButton) {
                $btn.button('reset');
            } else {
                copyBtn.disabled = false;
            }
            return;
        }

        clearPendingCopyTask();

        pendingCopyTask = {
            data: rowData,
            button: $btn,
            rawButton: copyBtn,
            timeoutId: window.setTimeout(() => {
                console.warn('[联动绑定] 等待复制弹框超时');
                clearPendingCopyTask();
            }, COPY_MODAL_TIMEOUT)
        };

        addBtn.click();
    }

    function handleCopyModalShown(event) {
        if (!pendingCopyTask) {
            return;
        }

        const modal = event.target;
        if (!modal || typeof modal.querySelector !== 'function') {
            return;
        }

        const form = modal.querySelector('#form-add');
        if (!form) {
            return;
        }

        try {
            fillAddForm(form, pendingCopyTask.data);
            console.log('[联动绑定] 复制弹框已根据列表数据回显');
        } catch (err) {
            console.error('[联动绑定] 复制弹框回显失败:', err);
        } finally {
            clearPendingCopyTask();
        }
    }

    function clearPendingCopyTask() {
        if (!pendingCopyTask) {
            return;
        }

        if (pendingCopyTask.timeoutId) {
            clearTimeout(pendingCopyTask.timeoutId);
        }

        const $btn = pendingCopyTask.button;
        if ($btn && typeof $btn.button === 'function') {
            $btn.button('reset');
        } else if (pendingCopyTask.rawButton) {
            pendingCopyTask.rawButton.disabled = false;
        }

        pendingCopyTask = null;
    }

    function findCopyButton(target) {
        let current = target;
        while (current && current !== document.body) {
            if (current.classList && current.classList.contains('jq-page-opt-copy')) {
                return current;
            }
            current = current.parentElement;
        }
        return null;
    }

    function getRowDataForButton(buttonEl) {
        const $ = window.jQuery;
        if (!$) {
            return null;
        }

        const $table = $('#page');
        if (!$table.length || typeof $table.bootstrapTable !== 'function') {
            return null;
        }

        const tableData = $table.bootstrapTable('getData') || [];
        const rowEl = findParentRow(buttonEl);
        if (rowEl) {
            const indexAttr = rowEl.getAttribute('data-index');
            const rowIndex = indexAttr ? parseInt(indexAttr, 10) : NaN;
            if (!isNaN(rowIndex) && tableData[rowIndex]) {
                return tableData[rowIndex];
            }
        }

        const id = buttonEl.getAttribute('data-id');
        if (id) {
            for (let i = 0; i < tableData.length; i++) {
                const item = tableData[i];
                if (String(item.id) === id) {
                    return item;
                }
            }
        }

        return null;
    }

    function findParentRow(element) {
        let current = element;
        while (current && current !== document.body) {
            if (current.tagName && current.tagName.toLowerCase() === 'tr') {
                return current;
            }
            current = current.parentElement;
        }
        return null;
    }

    function fillAddForm(formElement, rowData) {
        const $ = window.jQuery;
        if (!$ || !formElement) {
            return;
        }

        const $form = $(formElement);
        const setValue = (selector, value) => {
            const $field = $form.find(selector);
            if ($field.length) {
                $field.val(value == null ? '' : value);
            }
        };

        setValue('#form-add-name', rowData.name);
        setValue('#form-add-ckey', rowData.ckey);
        setValue('#form-add-cvalue', rowData.cvalue);
        setValue('#form-add-orderNum', rowData.orderNum);
        setValue('#form-add-remark', rowData.remark);

        const typeValue = rowData.type != null ? String(rowData.type) : '';
        const childValue = rowData.childType != null ? String(rowData.childType) : '';
        const statusValue = Number(rowData.status) === 2 ? '2' : '1';

        const $type = $form.find('#form-add-type');
        if ($type.length && typeValue) {
            $type.val(typeValue);
            $type.trigger('change');
        }

        const applyChildValue = () => {
            const $childSelect = $form.find('#form-add-childType');
            if (!$childSelect.length) {
                return;
            }
            if (childValue && $childSelect.find(`option[value="${childValue}"]`).length) {
                $childSelect.val(childValue);
            }
        };

        if (typeValue) {
            setTimeout(applyChildValue, 100);
        } else {
            applyChildValue();
        }

        const $status = $form.find('#form-add-status-' + statusValue);
        if ($status.length) {
            $status.prop('checked', true);
        }
    }
})();
